package api

import (
	"FeedXmh/app/dao"
	"fmt"
	jwt "github.com/gogf/gf-jwt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
)

var Feed_plan = feed_plan{}

type feed_plan struct{}

func (a *feed_plan) GET(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()

	id := gconv.String(params["id"])
	key := gconv.String(params["key"])

	where := " 1=1 "
	if id != "" {
		where += " and id=" + id
	}
	if key != "" {
		where += " and name like '%" + key + "%'"
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path

	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		//管理员可以看到全部，其他只能看到自己能看到的（分配的）
		if dao.IsAdmin(userid) || dao.IsService(userid) {

		} else {
			where += fmt.Sprintf(" and (FIND_IN_SET('%s',users) or create_user='%s')", userid, userid)
		}
		model := db.Model("t_feed_plan").Where(where)
		r, err := model.All()
		if err != nil {
			g.Log().Line().Error(err)
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			list := r.List()

			if len(list) > 0 {
				users, err := dao.T_user.GetList()
				if err != nil {
					g.Log().Line(true).Error(err)
				} else {
					for i := 0; i < len(list); i++ {
						create_user := gconv.String(list[i]["create_user"])
						for x := 0; x < len(users); x++ {
							userid := gconv.String(users[x]["userid"])
							name := gconv.String(users[x]["name"])
							if userid == create_user {
								list[i]["create_user_name"] = name
								break
							}
						}
						update_user := gconv.String(list[i]["update_user"])
						for x := 0; x < len(users); x++ {
							userid := gconv.String(users[x]["userid"])
							name := gconv.String(users[x]["name"])
							if userid == update_user {
								list[i]["update_user_name"] = name
								break
							}
						}
					}
				}
			}

			res["data"] = list
			res["count"] = len(list)
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *feed_plan) GetPage(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()
	limit := r.GetInt("limit")
	page := r.GetInt("page")
	order := r.GetString("order")

	id := gconv.String(params["id"])
	key := gconv.String(params["key"])

	where := " 1=1 "
	if id != "" {
		where += " and id=" + id
	}
	if key != "" {
		where += " and name like '%" + key + "%'"
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		//管理员可以看到全部，其他只能看到自己能看到的（分配的）
		if dao.IsAdmin(userid) || dao.IsService(userid) {

		} else {
			where += fmt.Sprintf(" and (FIND_IN_SET('%s',users) or create_user='%s')", userid, userid)
		}
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		model := db.Model("t_feed_plan")
		count, err := model.Where(where).Count()
		if err != nil {
			g.Log().Line().Error(err)
			res["msg"] = err.Error()
			res["code"] = -1
		} else {
			res["count"] = count
			start := limit*page - limit
			if start < 0 {
				start = 0
			}
			if order != "" {
				model = model.Order(order)
			}
			records, error := model.Limit(start, limit).All()
			if error != nil {
				g.Log().Line().Error(err)
				res["msg"] = err.Error()
				res["code"] = -1
			} else {
				list := records.List()
				if len(list) > 0 {
					users, err := dao.T_user.GetList()
					if err != nil {
						g.Log().Line(true).Error(err)
					} else {
						for i := 0; i < len(list); i++ {
							create_user := gconv.String(list[i]["create_user"])
							for x := 0; x < len(users); x++ {
								userid := gconv.String(users[x]["userid"])
								name := gconv.String(users[x]["name"])
								if userid == create_user {
									list[i]["create_user_name"] = name
									break
								}
							}
							update_user := gconv.String(list[i]["update_user"])
							for x := 0; x < len(users); x++ {
								userid := gconv.String(users[x]["userid"])
								name := gconv.String(users[x]["name"])
								if userid == update_user {
									list[i]["update_user_name"] = name
									break
								}
							}
						}
					}
				}

				res["data"] = list
				res["count"] = len(list)
				res["code"] = 0
				res["data"] = list
			}
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *feed_plan) PUT(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()

	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	url := r.URL.Path

	params["update_date"] = gtime.Now().String()
	params["update_user"] = current_user
	id := gconv.String(params["id"])

	if dao.CheckApiPermission(url, r.Method, current_user) {
		//情况对应t_user_farm后，重新添加
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		_, err := db.Model("t_feed_plan").Data(params).Save()
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			res["code"] = 0
			res["msg"] = "保存成功"
			res["data"] = id
		}

	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *feed_plan) POST(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()

	_, exist := params["id"]
	if exist {
		delete(params, "id")
	}

	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	url := r.URL.Path
	params["create_date"] = gtime.Now().String()
	params["create_user"] = current_user
	//id:= gconv.String(params["id"])

	//db:=g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, current_user) {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		re, err := db.Model("t_feed_plan").Data(params).Save()
		if err == nil {
			newid, _ := re.LastInsertId()
			res["code"] = 0
			res["msg"] = "保存成功"
			res["data"] = newid
		} else {
			res["code"] = -1
			res["msg"] = err.Error()
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *feed_plan) DELETE(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()

	id, exist := params["id"]
	if exist {
		claims := jwt.ExtractClaims(r)
		current_user := claims["userid"].(string)
		url := r.URL.Path
		//db:=g.DB(g.Cfg().GetString("custom.db_name"))
		if dao.CheckApiPermission(url, r.Method, current_user) {
			_, err := dao.T_feed_plan.Delete(gconv.String(id))
			if err != nil {
				g.Log().Line().Error(err)
				res["code"] = -1
				res["msg"] = err.Error()
			}
		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}
	} else {
		res["code"] = -1
		res["msg"] = "错误的参数"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *feed_plan) Allocate(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetFormMap()

	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)

	id := gconv.String(params["id"])
	users := gconv.String(params["users"])

	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, current_user) {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		list, err := dao.T_feed_plan.GetList(fmt.Sprintf("id=%s", id))
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			if len(list) > 0 {
				item := list[0]
				item["users"] = users
				_, err := db.Model("t_feed_plan").Data(item).Save()
				if err != nil {
					res["code"] = -1
					res["msg"] = err.Error()
				} else {
					res["code"] = 0
					res["msg"] = "保存成功"
					res["data"] = id
				}
			} else {
				res["code"] = -1
				res["msg"] = "参数错误"
			}
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}
